/*
 * Robot16Consumidor.h
 *
 *  Created on: Dec 1, 2013
 *      Author: m
 */

#ifndef ROBOT16CONSUMIDOR_H_
#define ROBOT16CONSUMIDOR_H_

#include "Semaphore.h"
#include "SharedMemory2.h"

using ipc::Semaphore;
using ipc::SharedMemory2;

class Robot16Consumidor
{
protected:
    static const std::string s_ipcBaseFile;
    static const char s_esperaProductoKey;
    static const char s_mutexKey;
    static const char s_semaphoreKey;

    bool *m_esperaProducto;
    Semaphore m_mutex;
    Semaphore m_semaphore;

public:
    Robot16Consumidor() :
        m_esperaProducto( SharedMemory2<bool>::get( s_ipcBaseFile,
                s_esperaProductoKey ) ),
        m_mutex( Semaphore::get( s_ipcBaseFile, s_mutexKey ) ),
        m_semaphore( Semaphore::get( s_ipcBaseFile, s_semaphoreKey ) )
    {
    }

    virtual ~Robot16Consumidor()
    {
    }

    void iniciarExclusionMutua()
    {
        m_mutex.p();
    }

    void terminarExclusionMutua()
    {
        m_mutex.v();
    }

    bool esperaProducto()
    {
        return *m_esperaProducto;
    }

    void setEsperaProducto( bool v )
    {
        *m_esperaProducto = v;
    }

    void dormir()
    {
        m_semaphore.p();
    }

    void despertar()
    {
        m_semaphore.v();
    }

    static void create()
    {
        *SharedMemory2<bool>::create( s_ipcBaseFile, s_esperaProductoKey )
                = false;
        Semaphore::create( s_ipcBaseFile, s_mutexKey ).initialize( 1 );
        Semaphore::create( s_ipcBaseFile, s_semaphoreKey ).initialize( 0 );
    }

    static void destroy()
    {
        SharedMemory2<bool>::destroy( s_ipcBaseFile, s_esperaProductoKey );
        Semaphore::destroy( s_ipcBaseFile, s_mutexKey );
        Semaphore::destroy( s_ipcBaseFile, s_semaphoreKey );
    }
};

#endif /* ROBOT16CONSUMIDOR_H_ */
